<template>
  <div class="mend-list container-box">
    <!-- 查询区域 -->
    <a-card class="card-header  block-box">
      <a-form-model :model="model">
        <a-row>
          <a-col :span="20">
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="处理状态"
                >
                  <a-select
                    v-model="model.resolve"
                    :allowClear="true"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    placeholder="请选择处理状态"
                    show-search
                    style="width: 100%;"
                  >
                    <a-select-option
                      v-for="(item, index) in statusOption"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="10">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 5 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 19 },
                  }"
                  label="时间范围"
                >
                  <a-range-picker
                    :placeholder="['开始时间', '结束时间']"
                    v-model="searchTime"
                    style="width:100%"
                    @change="onChange"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="7">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 9 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 15 },
                  }"
                  label="报警号/报警内容"
                >
                  <a-input
                    v-model="model.alarmNum"
                    placeholder="报警号/报警内容"
                    style="width:100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <!-- <br v-if="collseped" />
            <a-row v-if="collseped" :gutter="24">
              <a-col v-if="roleId != 1" :span="6">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="处理状态"
                >
                  <a-select
                    v-model="model.resolve"
                    :allowClear="true"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    placeholder="请选择处理状态"
                    show-search
                    style="width: 100%;"
                  >
                    <a-select-option
                      v-for="(item, index) in statusOption"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row> -->
          </a-col>
          <a-col :span="4">
            <a-row>
              <a-col style="display:flex;align-item:center">
                <!-- <div
                  :class="{ collseped: collseped }"
                  class="collseped-box"
                  @click="handleCollseped"
                >
                  <a-icon type="down" />
                  <span>{{ collsepedLabel }}</span>
                </div> -->
                <a-button
                  class="btn-1"
                  icon="search"
                  style="margin-right: 8px;"
                  type="primary"
                  @click="handleSearch"
                >
                  查询
                </a-button>
                <a-button class="btn-2" @click="handleReset">
                  <a-icon :spin="spin" type="sync" />
                  重置
                </a-button>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <br />
    <!-- 表格区域 -->
    <a-card class="card-content mt-20">
      <a-row>
        <a-col :span="15">
          <div class="ExportBox">
            <ExportFile
              :fetch="getDownloadData"
              :fields="jsonFields"
              name="报警记录.xls"
            >
              <a-button
                :loading="iconLoading"
                style="margin-right: 10px"
                type="primary"
              >
                导出
              </a-button>
            </ExportFile>
            <a-button
              style="background:#ECAB44;color:#FFFFFF "
              @click="handleMoreAlarm"
              >批量处理报警
            </a-button>
          </div>
        </a-col>
      </a-row>
      <div>
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="false"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :rowKey="(record, index) => record.id"
          :scroll="{ x: 2000 }"
        >
          <template slot="alarmNum" slot-scope="text, record">
            <div
              :style="{
                color: '#fff',
                'background-color': AlarmBack[record.alarmtype - 1],
                padding: '6px 8px',
                'font-weight': 'bold',
              }"
            >
              {{ record.alarmNum }}
            </div>
          </template>
          <!-- 状态 -->
          <template slot="resolve" slot-scope="text">
            <div class="resolveStaus">
              <div
                :style="{
                  'background-color': text === '1' ? '#51BB6F' : '#FF6D6D',
                }"
                class="circular"
              ></div>
              <div
                :style="{
                  color: text === '1' ? '#51BB6F' : '#FF6D6D',
                }"
              >
                {{ text === "1" ? "是" : "否" }}
              </div>
            </div>
          </template>
          <!-- 处理方式 -->
          <template slot="resolveMethod" slot-scope="text">
            <span style="color:#6D79FF">{{ text }}</span>
          </template>
          <!-- 状态区域-->
          <template slot="runstate" slot-scope="text">
            {{ runStateOptioncolor(text, 3) }}
          </template>
          <!-- 操作区域 -->
          <template slot="action" slot-scope="text, record">
            <a @click="handleAlarm(record)">编辑</a>
          </template>
        </a-table>
      </div>
      <div style="padding: 20px;text-align:right">
        <a-pagination
          v-model="model.pageNumber"
          :show-total="(total) => `共 ${total} 条记录`"
          :total="total"
          size="small"
          @change="changePage"
        />
      </div>
      <!-- 报警处理弹框 -->
      <AlarmModal ref="AlarmModal" @setData="setData" />
    </a-card>
  </div>
</template>
<script>
import api from "@/api/apiServer.js";
import moment from "moment";
import { computeData } from "@/unit/tool";
import ExportFile from "vue-json-excel";
import AlarmModal from "./components/AlarmModal.vue";
import { AlarmBack, columns, statusOption } from "./components/config";

export default {
  components: { ExportFile, AlarmModal },
  data() {
    return {
      model: {
        startTime: "",
        endTime: "",
        alarmNum: "",
        pageNumber: 1,
        pageSize: 10,
      },
      spin: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      columns,
      AlarmBack, // 报警号背景色
      total: 0, // 总页数
      tableData: [], // 表格数据
      loading: false, // 表格loading
      selectedRowKeys: [], //表格选中项
      iconLoading: false, // 导出loading
      jsonFields: this.buildJsonFields(columns), // 导出表头
      searchTime: [],
      statusOption,
      collseped: false,
    };
  },
  computed: {
    // 数控厂用户id
    roleId() {
      return localStorage.getItem("roleId");
    },
    // 用户信息
    userInfo() {
      return JSON.parse(localStorage.getItem("userInfo"));
    },
    collsepedLabel() {
      return this.collseped ? "收起" : "展开";
    },
    startTime() {
      return moment()
        .subtract(8, "days")
        .format("YYYY-MM-DD");
    },
    endTime() {
      return moment()
        .subtract(1, "days")
        .format("YYYY-MM-DD");
    },
  },
  created() {
    this.$set(this.model, "startTime", this.startTime);
    this.$set(this.model, "endTime", this.endTime);
    this.searchTime = [this.model.startTime, this.model.endTime];
    this.getList();
  },
  methods: {
    handleSearch() {
      this.model.pageNumber = 1;
      this.getList();
    },
    // 获取表格数据
    async getList() {
      this.loading = true;
      const res = await api.FindAlarmByParam(this.model);
      this.tableData = res.data.data;
      this.total = res.data.total;
      this.loading = false;
    },
    // 收起展开
    handleCollseped() {
      this.collseped = !this.collseped;
    },
    // 处理回调
    setData() {
      this.selectedRowKeys = [];
      this.getList();
    },
    // 重置
    handleReset() {
      this.spin = true;
      this.model = {
        startTime: "",
        endTime: "",
        alarmNum: "",
        pageNumber: 1,
        pageSize: 10,
      };
      this.$set(this.model, "startTime", this.startTime);
      this.$set(this.model, "endTime", this.endTime);
      this.searchTime = [this.model.startTime, this.model.endTime];
      this.getList();
      setTimeout(() => {
        this.spin = false;
      }, 1000);
      this.$forceUpdate();
    },
    // 表格选中回调
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 表格分页
    changePage(pageNumber) {
      this.model.pageNumber = pageNumber;
      this.getList();
    },
    // 日期时间选择器
    onChange(date, dateString) {
      this.$set(this.model, "startTime", dateString[0]);
      this.$set(this.model, "endTime", dateString[1]);
    },
    // 导出excel 表头处理
    buildJsonFields(lists) {
      let jsonFields = {};
      lists.forEach((item) => {
        if (item.dataIndex !== "conduct") {
          jsonFields[item.title] = item.dataIndex;
        }
      });
      return jsonFields;
    },
    // 导出
    async getDownloadData() {
      this.iconLoading = true;
      let total = this.total;
      // 单条数据
      const Single = await this.getSevenData({ pageNumber: 1, pageSize: 1 });
      // 单条数据 大小
      let SingleSize = computeData(Single);
      // 限制总大小
      let main = 20 * 1024 * 1024;
      // 可导出数量
      let num = Math.ceil(main / SingleSize);
      // 最大总页数
      let pageSize = 300;
      let MaxLength = Math.ceil(num / pageSize);
      let length = 0;
      // 判断当前后台接口返回的条数
      if (total > num) {
        length = MaxLength;
      } else {
        length = Math.ceil(total / pageSize);
      }
      let newLists = [];
      for (let i = 1; i <= length; i++) {
        let lists = await this.getSevenData({
          pageNumber: i,
          pageSize: pageSize,
        });
        newLists.push(lists);
      }
      this.iconLoading = false;
      return [].concat(...newLists);
    },
    // 获取七天前的数据
    async getSevenData(pagination) {
      const { data: res } = await api.FindAlarmByParam(this.model);
      this.total = res.total;
      return res.data.map((item) => {
        if (item.resolve === "1") {
          item.resolve = "是";
        } else {
          item.resolve = "否";
        }
        // item.macnumb = item.macnumb.toString();
        return item;
      });
    },
    handleAlarm(record) {
      this.$refs.AlarmModal.showModal();
      this.$refs.AlarmModal.model.ids = record.id.toString();
    },
    // 批量处理报警
    handleMoreAlarm() {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.AlarmModal.showModal();
        this.$refs.AlarmModal.model.ids = this.selectedRowKeys.toString();
      } else {
        this.$message.error("请选择需要处理的报警记录");
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("./index.less");
</style>
